<?php 
function GetUsers()
{
        $conn = getConnection();
        $result = $conn->query('SELECT * FROM People P');
        return $result;
}

function GetUser($id)
{
        $conn = getConnection();
        $result = $conn->query("SELECT * FROM People P WHERE ID=$id");
        $rs = $result->fetch_assoc();
        $conn->close();
        return $rs;
}

function SaveUser($rs)
{ 
		$conn = getConnection();
		$rs = RsEscape($conn, $rs);
        $result = $conn->query("UPDATE People P SET First_Name='$rs[First_Name]', Last_Name='$rs[Last_Name]', Password='$rs[Password]' , SecurityLevel='$rs[SecurityLevel]', WHERE ID=$rs[ID]");     
        $error = $conn->error;
        $conn->close();
        return $error ? array('Server Error'=> $error) : Null;
        
}

function ValidateUser($rs)
{ 
	$errors = Null;
	if(empty($rs['First_Name']))
	{
		$errors['First_Name'] = 'First Name is required';
	}
	if(empty($rs['Last_Name']))
	{
		$errors['Last_Name'] = 'First Name is required';
	}
    if(empty($rs['Address_Line1']))
	{
		$errors['Address_Line1'] = 'Address Line 1 is required';
	}
    if(empty($rs['City']))
	{
		$errors['City'] = 'City is required';
	}
    if(empty($rs['State']))
	{
		$errors['State'] = 'Please select a state from the drop down list';
	}
    if(empty($rs['Zipcode']))
	{
		$errors['Zipcode'] = 'Zipcode is required';
	}
    if(empty($rs['Email']))
	{
		$errors['Email'] = 'Email is required';
	}
	if(strlen($rs['Password']) < 6)
	{
		$errors['Password'] = 'Password is too short.  It must be at least 6 characters long.';
	}
	
	return $errors;
	
}

function DeleteUser($id)
{
	
		$conn = getConnection();
        $result = $conn->query("DELETE FROM People WHERE ID=$id");     
        $error = $conn->error;
        $conn->close();
		return $error ? array('Server Error'=> $error) : Null;
	
}

function AddUser($rs)
{
		$conn = getConnection();
		$rs = RsEscape($conn, $rs);
		$sql = 'INSERT INTO People ' 
			   .'(First_Name, Last_Name, Password, SecurityLevel, Created_at) '
			   ."VALUES ('$rs[First_Name]', '$rs[Last_Name]', '$rs[Password]', 'Customer', Now()) ";
		$sql .= 'INSERT INTO Addresses '
				.'(Address_Line1, Address_Line2, City, State, Zipcode, Created_at) '
				."VALUES('$rs[Address_Line1]', '$rs[Address_Line2]', '$rs[City]', '$rs[State]', '$rs[Zipcode]', Now()) ";
		$sql .= 'INSERT INTO ConnectionMethods '
				.'(Category_ID, Value, Created_at) '
				."VALUES(2, '$rs[Phone]', Now())";
		//How do I get a value like person ID into the ConnectionMethods table "on the fly"?
        $result = $conn->multi_query($sql);     
        $error = $conn->error;
        $conn->close();
		return $error ? array('Server Error'=> $error) : Null;
	
}

function NewUser()
{
	return array('First_Name'=>'', 'Last_Name'=>'', 'Password'=>'', 'SecurityLevel' =>'', 'ID'=>Null, 'Created_at'=>Null, 'Updated_at'=>Null);
}

?>